package com.mantou.cdl.proxy;

import java.util.ArrayList;
import java.util.List;

import com.mantou.cdl.task.User;
import com.mantou.cdl.utils.BloomFilter;
import com.mantou.cdl.utils.BloomFilter32bit;
import com.mantou.cdl.utils.SysConfig;



public class ProxyIpServiceImpl implements ProxyIpService{
	
	public static List<ProxyAddress> ipList = null;
	private int resorceNumbers = 400;
	private AbstractProxyImporter proxyImproter ;
	private BloomFilter allocatedSource = new BloomFilter32bit(SysConfig.proxyspace, 20);// i don`t know the function of second argument

	
	public int getResorceNumbers() {
		return resorceNumbers;
	}
	public void setResorceNumbers(int resorceNumbers) {
		this.resorceNumbers = resorceNumbers;
	}
	public void init(){// now it`s hard code
		proxyImproter = new XICIProxyImporter();
		ipList = proxyImproter.getSource(resorceNumbers,allocatedSource);
	}
	public List<ProxyAddress> queryProxyIps() {
		// TODO Auto-generated method stub
		return ipList;
	}

	public void cleanResource(User user, int expectNumbers) {
		// TODO Auto-generated method stub
		if(ipList == null){
			init();
		}
		if(ipList == null)
			return;
		List<ProxyAddress> proxyspce = user.getProxspace();
		if(proxyspce == null){
			proxyspce = new ArrayList<ProxyAddress>();
		}
		for(ProxyAddress proxyAddress:proxyspce){
			if(proxyAddress.getFailTimes() >= SysConfig.proxyDeprecatedTimes){
				allocatedSource.add(proxyAddress.getIp());
				proxyspce.remove(proxyAddress);
			}
		}
		
		if(proxyspce.size() < expectNumbers){//mean that we need add proxy resource
			int addnumber = expectNumbers - proxyspce.size();
			int remainNumber = ipList.size();
			
			if(addnumber <= remainNumber){//service resource enough
				while(addnumber > 0){
					proxyspce.add(ipList.remove(0));
					addnumber --;
				}
				return;
			}else{
				while(remainNumber > 0){
					proxyspce.add(ipList.remove(0));
					remainNumber --;
				}
			}
			ipList.addAll(proxyImproter.getSource(addnumber - remainNumber+ resorceNumbers, allocatedSource));
			
			int newAddNumber = addnumber - remainNumber;
			while(newAddNumber > 0){
				proxyspce.add(ipList.remove(0));
				remainNumber --;
			}
			
		}
	}
	
	
	
}
